from django.conf import settings
from django.core.paginator import Paginator
from django.db.models import Count
from django.shortcuts import get_object_or_404, render
from readstat.utils import readstat_once_read

from .models import Blog, BlogType
from user.forms import LoginForm

# Create your views here.


def get_blog_list_common_data(request, blogs_all_list):
    pages = Paginator(blogs_all_list, settings.EACH_PAGE_BLOG_NUMBERS)
    total_num = pages.num_pages
    page_num = int(request.GET.get('page', 1))
    page_range = list(
        range(max(1, page_num - 1),
              min(total_num, page_num + 1) + 1))
    if page_range[0] - 1 >= 2:
        page_range.insert(0, '...')
    if total_num - page_range[-1] >= 2:
        page_range.append('...')
    if page_range[0] != 1:
        page_range.insert(0, 1)
    if page_range[-1] != total_num:
        page_range.append(total_num)

    blog_dates = Blog.objects.dates('c_time', 'month', order='DESC')
    blog_dates_dict = {}
    for blog_date in blog_dates:
        blog_count = Blog.objects.filter(
            c_time__year=blog_date.year,
            c_time__month=blog_date.month).count()
        blog_dates_dict[blog_date] = blog_count

    blog_count = BlogType.objects.annotate(blog_count=Count('blog'))

    context = {}
    context['pg_list'] = pages.get_page(page_num)
    context['pg_range'] = page_range
    context['blog_types'] = blog_count
    context['blog_dates'] = blog_dates_dict
    return context


def blog_list(request):
    blogs_all_list = Blog.objects.all()
    context = get_blog_list_common_data(request, blogs_all_list)
    return render(request, 'blog/blog_list.html', context)


def blog_detail(request, blog_pk):
    blog = get_object_or_404(Blog, pk=blog_pk)
    key = readstat_once_read(request, blog)

    pre_blog = Blog.objects.filter(c_time__gt=blog.c_time).last()
    next_blog = Blog.objects.filter(c_time__lt=blog.c_time).first()

    context = {}
    context['blog'] = blog
    context['pre_blog'] = pre_blog
    context['next_blog'] = next_blog
    context['login_form'] = LoginForm()
    response = render(request, 'blog/blog_detail.html', context)
    response.set_cookie(key, 'true')
    return response


def type_list(request, type_pk):
    blog_type = get_object_or_404(BlogType, pk=type_pk)
    blogs_all_list = Blog.objects.filter(blog_type=blog_type)
    context = get_blog_list_common_data(request, blogs_all_list)
    context['blog_type'] = blog_type
    return render(request, 'blog/type_list.html', context)


def blogs_with_date(request, year, month):
    blogs_all_list = Blog.objects.filter(
        c_time__year=year, c_time__month=month)
    context = get_blog_list_common_data(request, blogs_all_list)
    context['blogs_with_date'] = '%s年%s月' % (year, month)
    return render(request, 'blog/blogs_with_date.html', context)
